const { query } = require('../config/database');
const Post = require('./Post');

class PostComment {
  /**
   * 创建评论
   * @param {number} postId - 动态ID
   * @param {string} userId - 用户ID
   * @param {string} content - 评论内容
   * @param {number|null} parentId - 父评论ID（回复时使用）
   * @returns {Object} 创建的评论信息
   */
  static async create(postId, userId, content, parentId = null) {
    try {
      // 参数验证
      if (!content || content.trim().length === 0) {
        throw new Error('评论内容不能为空');
      }
      
      if (content.length > 500) {
        throw new Error('评论内容不能超过500个字符');
      }
      
      // 验证动态是否存在
      const post = await Post.getById(postId, userId);
      if (!post) {
        throw new Error('动态不存在');
      }
      
      // 如果是回复，验证父评论是否存在
      if (parentId) {
        const parentComment = await PostComment.getById(parentId, userId);
        if (!parentComment || parentComment.postId !== postId) {
          throw new Error('父评论不存在或不属于该动态');
        }
      }

      const insertSql = `
        INSERT INTO post_comments (post_id, user_id, content, parent_id) 
        VALUES (?, ?, ?, ?)
      `;
      
      const result = await query(insertSql, [postId, userId, content.trim(), parentId]);
      
      // 获取刚创建的评论
      return await PostComment.getById(result.insertId, userId);
    } catch (error) {
      console.error('创建评论失败:', error);
      throw error;
    }
  }

  /**
   * 根据ID获取评论详情
   * @param {number} commentId - 评论ID
   * @param {string} currentUserId - 当前用户ID
   * @returns {Object|null} 评论信息
   */
  static async getById(commentId, currentUserId) {
    try {
      const sql = `
        SELECT 
          c.id,
          c.post_id as postId,
          c.user_id as userId,
          u.nick_name as userNickName,
          u.avatar as userAvatar,
          c.content,
          c.parent_id as parentId,
          c.created_at as createdAt,
          -- 父评论信息
          CASE 
            WHEN c.parent_id IS NOT NULL THEN (
              SELECT JSON_OBJECT(
                'id', pc.id,
                'userId', pc.user_id,
                'userNickName', pu.nick_name,
                'content', pc.content
              )
              FROM post_comments pc
              LEFT JOIN users pu ON pc.user_id = pu.user_id
              WHERE pc.id = c.parent_id AND pc.status = 1
            )
            ELSE NULL
          END as parentComment
        FROM post_comments c
        LEFT JOIN users u ON c.user_id = u.user_id
        WHERE c.id = ? AND c.status = 1
      `;
      
      const comments = await query(sql, [commentId]);
      
      if (comments.length > 0) {
        const comment = comments[0];
        // 解析JSON字符串
        if (comment.parentComment) {
          comment.parentComment = JSON.parse(comment.parentComment);
        }
        return comment;
      }
      
      return null;
    } catch (error) {
      console.error('获取评论详情失败:', error);
      throw error;
    }
  }

  /**
   * 获取动态评论列表
   * @param {number} postId - 动态ID
   * @param {string} currentUserId - 当前用户ID
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @returns {Object} 评论列表和分页信息
   */
  static async getCommentsByPostId(postId, currentUserId, page = 1, limit = 20) {
    try {
      // 验证动态是否存在
      const post = await Post.getById(postId, currentUserId);
      if (!post) {
        throw new Error('动态不存在');
      }
      
      // 确保参数为整数类型
      page = parseInt(page);
      limit = parseInt(limit);
      
      const offset = (page - 1) * limit;
      
      // 获取评论列表（只获取顶级评论，回复作为子评论）
      const sql = `
        SELECT 
          c.id,
          c.post_id as postId,
          c.user_id as userId,
          u.nick_name as userNickName,
          u.avatar as userAvatar,
          c.content,
          c.parent_id as parentId,
          c.created_at as createdAt,
          -- 回复数量
          (SELECT COUNT(*) FROM post_comments WHERE parent_id = c.id AND status = 1) as replyCount
        FROM post_comments c
        LEFT JOIN users u ON c.user_id = u.user_id
        WHERE c.post_id = ? AND c.status = 1 AND c.parent_id IS NULL
        ORDER BY c.created_at ASC
        LIMIT ${limit} OFFSET ${offset}
      `;
      
      const comments = await query(sql, [postId]);
      
      // 为每个评论获取最新的几条回复
      for (let comment of comments) {
        if (comment.replyCount > 0) {
          const replySql = `
            SELECT 
              c.id,
              c.user_id as userId,
              u.nick_name as userNickName,
              u.avatar as userAvatar,
              c.content,
              c.created_at as createdAt
            FROM post_comments c
            LEFT JOIN users u ON c.user_id = u.user_id
            WHERE c.parent_id = ? AND c.status = 1
            ORDER BY c.created_at ASC
            LIMIT 3
          `;
          
          comment.replies = await query(replySql, [comment.id]);
        } else {
          comment.replies = [];
        }
      }
      
      // 获取总数
      const countSql = `
        SELECT COUNT(*) as total 
        FROM post_comments 
        WHERE post_id = ? AND status = 1 AND parent_id IS NULL
      `;
      
      const countResult = await query(countSql, [postId]);
      const total = countResult[0].total;
      
      return {
        comments,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('获取评论列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取评论的回复列表
   * @param {number} commentId - 评论ID
   * @param {string} currentUserId - 当前用户ID
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @returns {Object} 回复列表和分页信息
   */
  static async getReplies(commentId, currentUserId, page = 1, limit = 20) {
    try {
      // 验证父评论是否存在
      const parentComment = await PostComment.getById(commentId, currentUserId);
      if (!parentComment) {
        throw new Error('评论不存在');
      }
      
      // 确保参数为整数类型
      page = parseInt(page);
      limit = parseInt(limit);
      
      const offset = (page - 1) * limit;
      
      const sql = `
        SELECT 
          c.id,
          c.post_id as postId,
          c.user_id as userId,
          u.nick_name as userNickName,
          u.avatar as userAvatar,
          c.content,
          c.parent_id as parentId,
          c.created_at as createdAt
        FROM post_comments c
        LEFT JOIN users u ON c.user_id = u.user_id
        WHERE c.parent_id = ? AND c.status = 1
        ORDER BY c.created_at ASC
        LIMIT ${limit} OFFSET ${offset}
      `;
      
      const replies = await query(sql, [commentId]);
      
      // 获取总数
      const countSql = `
        SELECT COUNT(*) as total 
        FROM post_comments 
        WHERE parent_id = ? AND status = 1
      `;
      
      const countResult = await query(countSql, [commentId]);
      const total = countResult[0].total;
      
      return {
        replies,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('获取回复列表失败:', error);
      throw error;
    }
  }

  /**
   * 删除评论
   * @param {number} commentId - 评论ID
   * @param {string} userId - 用户ID
   * @returns {boolean} 删除结果
   */
  static async delete(commentId, userId) {
    try {
      // 验证评论是否存在且属于当前用户
      const checkSql = `
        SELECT id, post_id FROM post_comments 
        WHERE id = ? AND user_id = ? AND status = 1
      `;
      
      const comments = await query(checkSql, [commentId, userId]);
      
      if (comments.length === 0) {
        throw new Error('评论不存在或无权限删除');
      }
      
      // 软删除评论（同时删除所有回复）
      const deleteSql = `
        UPDATE post_comments 
        SET status = 0 
        WHERE (id = ? OR parent_id = ?)
      `;
      
      await query(deleteSql, [commentId, commentId]);
      return true;
    } catch (error) {
      console.error('删除评论失败:', error);
      throw error;
    }
  }
}

module.exports = PostComment;